<template>
  <div class="edit-form edit-dialog">
    <el-form
      :model="state.editForm"
      :rules="state.rules"
      ref="editFormRef"
      label-width="100px"
      class="demo-editData"
      v-loading="loading"
    >
      <el-descriptions
        :column="2"
        border
        :colon="true"
        label-class-name="custom-description-label-160"
      >
        <el-descriptions-item>
          <template #label>
            <span class="colorRed">*</span>
            登录名
          </template>
          <el-form-item prop="userName">
            <el-input
              type="text"
              v-model="state.editForm.userName"
              placeholder="请输入"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <span class="colorRed">*</span>
            名称
          </template>
          <el-form-item prop="realName">
            <el-input
              type="text"
              v-model="state.editForm.realName"
              placeholder="请输入"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template #label>联系电话</template>
          <el-form-item>
            <el-input
              type="text"
              v-model="state.editForm.telephone"
              placeholder="请输入"
              maxlength="50"
            ></el-input>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template #label>
            <span class="colorRed">*</span>
            所属机构
          </template>
          <el-form-item prop="orgId" :rules="$formRules.select">
            <el-cascader
              ref="cascaderRef"
              v-model="state.selectValue"
              :filterable="true"
              :show-all-levels="true"
              :options="state.options"
              :props="{ checkStrictly: true }"
              style="width: 100%"
              @change="change"
            ></el-cascader>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item :span="2">
          <template #label>备注</template>
          <el-form-item>
            <el-input
              type="textarea"
              maxlength="200"
              show-word-limit
              v-model="state.editForm.remark"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-descriptions-item>
      </el-descriptions>
    </el-form>
    <div class="btn-group">
      <el-button class="btn-form-close" @click="close()">取消</el-button>
      <el-button
        class="btn-form-save"
        type="primary"
        @click="submitForm(editFormRef)"
      >
        保存
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeMount, watch } from 'vue'
import { getOrgOptions, getAccountEditInfos } from '@/api/system'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useUserStore } from '@/pinia/modules/user'
import {
  Delete,
  Edit,
  Search,
  Share,
  Upload,
  Plus
} from '@element-plus/icons-vue'

const props = defineProps({
  editId: String,
  isEdit: Boolean
})

const loading = ref(false)
const state = reactive({
  options: [],
  selected: {},
  selectValue: [],
  editForm: {
    userName: '',
    realName: '',
    telephone: '',
    orgId: '',
    remark: '',
    orgCode: '',
    orgName: ''
  },
  rules: {
    userName: [
      {
        required: true,
        message: '请输入用户名',
        trigger: 'blur'
      }
    ],
    realName: [
      {
        required: true,
        message: '请输入登录账号',
        trigger: 'blur'
      }
    ],
    passWord: [
      {
        required: true,
        message: '请输入登录密码',
        trigger: 'blur'
      }
    ],
    telephone: [
      {
        required: true,
        message: '请输入手机号',
        trigger: 'blur'
      },
      {
        // validator: ,
        trigger: 'blur'
      }
    ],
    orgName: [
      {
        required: true,
        message: '请选择机构',
        trigger: 'blur'
      }
    ]
  }
})
const cascaderRef = ref(null)
const editFormRef = ref(null)
const emit = defineEmits(['close', 'submitForm'])

const change = val => {
  state.selected = cascaderRef.value.getCheckedNodes()[0].data
  state.editForm.orgCode = state.selected.code
  state.editForm.orgName = state.selected.label
  state.editForm.orgId = state.selected.id
}
//递归组织树获取默认值数组
const getArr = (dataSource, id) => {
  var arrRes = []
  let rev = (data, nodeId) => {
    for (var i = 0, length = data.length; i < length; i++) {
      let node = data[i]
      if (node.id == nodeId) {
        arrRes.unshift(node.id)
        rev(dataSource, node.pid)
        break
      } else {
        if (node.children != null) {
          rev(node.children, nodeId)
        }
      }
    }
    return arrRes
  }
  arrRes = rev(dataSource, id)
  return arrRes
}
const getTree = async () => {
  // let data = { orgType: '1' }
  let res = await getOrgOptions()
  console.log(res)
  if (res.succeed) {
    if (res.data[0] !== null) {
      state.options = createTree(res.data)
      if (state.selectValue) {
        state.selectValue = getArr(state.options, state.editForm.orgId)
      }
    } else {
      state.options = []
    }
  }
}
const createTree = org => {
  let orgArray = []
  org.forEach(item => {
    let o = {
      value: item.id,
      id: item.id,
      label: item.orgName,
      code: item.orgCode,
      pid: item.orgPid
    }

    if (item.children && item.children.length > 0)
      o.children = createTree(item.children)
    orgArray.push(o)
  })
  return orgArray
}
const init = async () => {
  loading.value = true
  let res = await getAccountEditInfos(props.editId)
  state.editForm = res.data
  loading.value = false
}
const close = () => {
  emit('close')
}
const load = () => {
  loading.value = false
}
const submitForm = formEl => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      loading.value = true
      state.editForm.orgType = '1' // 政府机构
      emit('submitForm', state.editForm)
    }
  })
}
const changeOrg = value => {}
const selectedChange = e => {
  state.editForm.orgCode = e.code
  state.editForm.orgName = e.label
}
watch(
  state.options,
  (newValue, oldValue) => {
    if (state.selectValue) {
      // state.selectValue = getArr(state.options, state.editForm.orgId)
    }
  },
  {
    deep: true,
    immediate: true
  }
)
watch(
  state.editForm,
  (newValue, oldValue) => {
    if (newValue.orgId) {
      state.selectValue = getArr(state.options, state.editForm.orgId)
    }
  },
  {
    deep: true,
    immediate: true
  }
)
defineExpose({
  load
})
onBeforeMount(async () => {
  // 获取机构树
  if (props.isEdit) {
    await init()
  }
  getTree()
})
</script>
<style scoped></style>
